import {createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
import { defineAsyncComponent } from 'vue'
import sessionStorage from "../utils/session"

export const constantRouterMap = [
	{
		path: '/',
		name: 'home',
		component: defineAsyncComponent(() => import(`../views/index.vue`)),
		meta: {
			title: '首页',
		},
	},
	{
		path: '/login',
		name: 'login',
		component: defineAsyncComponent(() => import(`../views/user/userLogin.vue`)),
		meta: {
			title: '登录',
		},
	},
	{
		path: '/reg',
		name: 'reg',
		component: defineAsyncComponent(() => import(`../views/user/reg.vue`)),
		meta: {
			title: '注册',
		},
	},
	{
		path: '//*',
		redirect: '/',
	},
]

export const asyncRouterMap = []

const router = createRouter({ 
  history: createWebHashHistory(),  // hash 模式
  // history: createWebHistory(),  // history 模式
  routes: constantRouterMap
})

// 全局路由守卫
router.beforeEach((to, from, next)=>{
	console.log(to);
  //用户访问的是'/home'
  if(to.path === '/home' || to.path === '/') {
    //查看一下用户是否保存了登录状态信息
    let user = JSON.parse(sessionStorage.getSession('shsUserInfo'))
    if(user) {
      //如果有，直接放行
      next();
    }else {
      //如果没有，用户跳转登录页面登录
      next('/login')
    }
  }else {
    next()
  }
})

router.afterEach((to, from)=>{
  console.log('afterEach')
})

export default router